package org.jiuling.network.tools.http.request.factory.impl;

import org.jiuling.local.tools.exception.LocalToolsException;
import org.jiuling.local.tools.util.InputStreamUtil;
import org.jiuling.local.tools.verify.ObjectVerify;
import org.jiuling.network.tools.http.request.exception.RequestException;
import org.jiuling.network.tools.http.request.factory.HttpRequestFactory;
import org.jiuling.network.tools.http.request.model.HttpResponse;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

/**
 * http请求工厂实现类
 * @author 紫灵
 * @date 2022年04月15日 19时36分23秒
 */
public class HttpRequestImpl extends HttpRequestConfig implements HttpRequestFactory {

    public HttpResponse send(String path) throws IOException, RequestException, LocalToolsException {
        // 获取远程连接并强制转换为HTTP远程连接
        HttpURLConnection httpURLConnection = (HttpURLConnection)super.getURLConnection(path);
        // 设置请求方式
        httpURLConnection.setRequestMethod(super.requestMethod.getMethod());
        // 链接请求
        super.connect(httpURLConnection);

        HttpResponse httpResponse = new HttpResponse();
        httpResponse.setHttpResponseStatus(httpURLConnection.getResponseCode());

        // 处理错误流信息
        try (InputStream errorInputStream = httpURLConnection.getErrorStream()){
            if(!ObjectVerify.isNull(errorInputStream)){
                httpResponse.setErrorBody(InputStreamUtil.readInputStream(errorInputStream));
                // 读取数据后关闭流
                errorInputStream.close();
            }
        }catch (FileNotFoundException ignored){
            // 该异常不处理
        }

        // 处理数据流信息
        try (InputStream inputStream = httpURLConnection.getInputStream()){
            if(!ObjectVerify.isNull(inputStream)){
                httpResponse.setBody(InputStreamUtil.readInputStream(inputStream));
            }
        }catch (FileNotFoundException ignored){
            // 该异常不处理
        }
        // 断开链接
        httpURLConnection.disconnect();
        return httpResponse;
    }

}
